package com.kylin.artwork.openapi.starter.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

//@Configuration
//@EnableCaching
public class RedisCacheConfigure extends CachingConfigurerSupport {

    private final ObjectMapper mapper = new ObjectMapper();

    //@Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @SuppressWarnings("rawtypes")
    //@Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        //RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        //rcm.setDefaultExpiration(60);//秒
        return null;//rcm;
    }

//    @Bean
    public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory factory) {
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        Jackson2JsonRedisSerializer<String> serializer =
                new Jackson2JsonRedisSerializer<>(String.class);
        serializer.setObjectMapper(mapper);

        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.afterPropertiesSet();
        template.setValueSerializer(serializer);
        return template;
    }
}
